package com.tmc.service.intair;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.intair.EthBookingReq;
import com.tmc.bean.intair.EthBookingResp;
import com.tmc.bean.intair.EthFare;
import com.tmc.constant.OrderConstant;
import com.tmc.entity.intair.IntairFare;
import com.tmc.entity.intair.IntairFlight;
import com.tmc.entity.intair.IntairOrder;
import com.tmc.entity.intair.IntairPassenger;
import com.tmc.service.cache.CacheServiceImpl;
import com.tmc.util.DateUtil;
import com.tmc.util.IntairUtil;
import com.tmc.util.ObjectUtil;
import com.tmc.vendor.intair.common.ServiceCenter;
import com.tmc.vendor.intair.common.VendorService;

@Service
public class EthBookingServiceImpl {

	@Autowired
	private CacheServiceImpl cache;
	
	@Autowired
	private IntairOrderServiceImpl orderSer;
	
	private Log log = LogFactory.getLog(this.getClass());
	
	public CommonResult booking(ContextInfo context, EthBookingReq req) {
		if (ObjectUtil.noText(req.getFareKey())){
			return CommonResult.makeFail("fareKey不能为空！");
		}
		if (req.getPassengers() == null || req.getPassengers().isEmpty()){
			return CommonResult.makeFail("乘机人不能为空！");
		}
		CommonResult cacheResul = IntairUtil.getFareFromCache(req.getFareKey(), cache);
		if (!cacheResul.isSuccess()){
			return cacheResul;
		}
		EthFare fare = (EthFare)cacheResul.getObj();
		VendorService service = ServiceCenter.getService(fare.getGds());
		EthBookingResp resp = null;
		try {
			req.setFlights(fare.getFlights());
			resp = service.booking(context, req);
			if (!resp.isSuccess()) {
			    return CommonResult.makeSuccess("成功", resp.getMessage());
			}
			IntairOrder order = this.buildOrder(context, fare, req, resp);
		    CommonResult cr = orderSer.save(context, order);
		    if (!cr.isSuccess()) {
		    	    return cr;
		    }
		} catch (Exception e) {
			log.error("booking出错", e);
			return CommonResult.makeFail("预订出错！代码102");
		}
		return CommonResult.makeSuccess("成功", resp);
	}

	private IntairOrder buildOrder(ContextInfo context, EthFare fare, EthBookingReq req, EthBookingResp resp) {
		IntairOrder order = new IntairOrder();
		order.setBookId(context.getUserId());
		order.setFare(ObjectUtil.makeTargetBean(fare, IntairFare.class));
		order.setFlights(ObjectUtil.makeTargetList(req.getFlights(), IntairFlight.class));
		order.setPassengers(ObjectUtil.makeTargetList(req.getPassengers(), IntairPassenger.class));
		order.setSource(OrderConstant.OrderSource.WEB.getSource());
		order.setBookDate(DateUtil.toLongDate(new Date()));
		return order;
	}
}
